import React, { PropsWithChildren, useRef, useEffect } from "react";
import HomeHeader from "./HomeHeader";
import { connect, useDispatch } from "react-redux";
import homeDispatchAction from "@/store/actions/home";
import { CustomCombinedState } from "@/store/reducers";
import { HomeState } from "@/store/reducers/home";
import { RouteComponentProps } from "react-router-dom";
import HomeSliders from "./HomeSliders";
import LessonList from "./LessonList/index";
import { loadMore, downRefresh, store } from "@/utils";
import { Icon } from "bigbear-ui";
import useGetWidth from "@/components/hooks/useGetWidth";
const mapStateToProps = (state: CustomCombinedState): HomeState => state.home;

type HomeProps = PropsWithChildren<RouteComponentProps & HomeState>;

function Home(props: HomeProps) {
	const homeContainer: React.RefObject<HTMLDivElement> = useRef(null);
	const refresh: React.RefObject<HTMLDivElement> = useRef(null);
	const dispatch = useDispatch();
	const width = useGetWidth();
	useEffect(() => {
		let ref = homeContainer.current;
		let refreshRef = refresh.current;
		loadMore(ref as HTMLDivElement, () => dispatch(homeDispatchAction.getLessons()));
		downRefresh(
			ref as HTMLDivElement,
			() => dispatch(homeDispatchAction.refreshLessons()),
			refreshRef as HTMLDivElement
		);
		setTimeout(() => {
			ref!.scrollTop = parseFloat(store.get("homeScrollTop") || "0");
		}, 200);

		return () => {
			store.set("homeScrollTop", ref?.scrollTop + "");
		};
	}, [dispatch]);
	return (
		<>
			<HomeHeader></HomeHeader>
			<div
				className="home-refresh-none"
				ref={refresh}
				key="refresh"
				style={{ position: "absolute", width }}
			>
				<Icon icon="angle-down"></Icon>
				<span>下拉刷新</span>
			</div>
			<div className="home-container" ref={homeContainer}>
				<HomeSliders sliders={props.sliders}></HomeSliders>
				<LessonList
					container={homeContainer}
					lessons={props.lessons}
					getLessons={() => dispatch(homeDispatchAction.getLessons())}
				/>
			</div>
		</>
	);
}

export default connect(mapStateToProps)(Home);
